App = {
  web3Provider: null,
  contracts: {},

  shopcarArray: [],  //购物车数组

  init: async function () {
    // Load shopmal.
    return await App.initWeb3();
  },

  initWeb3: async function () {
    // Modern dapp browsers...
    if (window.ethereum) {
      console.log('1')
      App.web3Provider = window.ethereum;
      try {
        // Request account access
        await window.ethereum.enable();
      } catch (error) {
        // User denied account access...
        console.error("User denied account access")
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      console.log('2')
      App.web3Provider = window.web3.currentProvider;
    }
    // If no injected web3 instance is detected, fall back to Ganache
    else {
      console.log('3')
      App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function () {
    // 加载Adoption.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
    $.getJSON('Adoption.json', function (data) {
      // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。
      App.contracts.Adoption = TruffleContract(data);

      // Set the provider for our contract
      App.contracts.Adoption.setProvider(App.web3Provider);

      App.contracts.Adoption.deployed().then(function(instance){
        App.adoptionInstance = instance;
        return App.getShopcars();
      })
      // Use our contract to retrieve and mark the adopted pets
     
    });
    return App.bindEvents();
  },

  bindEvents: function () {
    $(document).on('click', '.btn-adopt', App.addshop);
    $(document).on('click', '.back', App.jump);
    $(document).on('click', '.choose', App.select);
    $(document).on('click', '.pay', App.pay);
    $(document).on('click', '.chooseall', App.selectall);
  },

  getShopcars: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      // 获取购物车
      App.adoptionInstance.getShopcars(account).then(function(shopcars){
        var petsRow = $('#shopmal');
        var petTemplate = $('#shopTemplate');
        var cardwidth = $(window).width() - 99;
        $.getJSON('../pets.json', function (data) {
          for (i = 0; i < shopcars.length; i++) {
            if(shopcars[i]!= 0){
              let amount = '×'+ shopcars[i]
              petTemplate.find('.card').css("width",cardwidth);
              petTemplate.find('.name').text(data[i].name);
              petTemplate.find('.price').text(data[i].price);
              petTemplate.find('.img').attr('src', data[i].picture);
              petTemplate.find('.amount').text(amount);
              petTemplate.find('.amount').attr('id', data[i].id);
              petTemplate.find('.choose').attr('data-id', data[i].id);
              petTemplate.find('.btn-adopt').attr('data-id', data[i].id);
              petsRow.append(petTemplate.html());
            }
           
          };        
        })
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  getShopcar: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      // 发送交易获取购物车
      App.adoptionInstance.getShopcars(account).then(function(shopcars){
        $.getJSON('../pets.json', function (data) {
          for (i = 0; i < shopcars.length; i++) {
            if(shopcars[i]!= 0){
              let amount = '×'+ shopcars[i]  
              let id = '#' + i  
              $(id).text(amount);          
            }
           
          };        
        })
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  addshop: function (event) {
    event.preventDefault();
    var shopId = parseInt($(event.target).data('id'));
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log('addshop',error);
      }
      var account = accounts[0];
      App.adoptionInstance.addshop(shopId, { from: account }).then(function(){
        return App.getShopcar();
      }).catch(function (err) {
        console.log('addshoperr',err.message);
      });
    });
  },

  select: function (event) {
    event.preventDefault();
    if($(event.target).children("img").length == 1){  //img displaynone,点击的是div
      $(event.target).removeClass('unselect')
      $(event.target).addClass('select')
      $(event.target).children("img").css("display","block")
      //$(event.target).append('<img style="width:24px;height:24px;" src="images/selected.png">')     
    }
    else {     //点击的是img
      $(event.target).css("display","none")
      $(event.target).parent().removeClass('select')
      $(event.target).parent().addClass('unselect')
    }
   
    //parseInt($(event.target).data('id'));
  },

  selectall: function (event) {
    event.preventDefault();
    if($(event.target).children("img").length == 1){  //img displaynone,点击的是div,未选中->选中
      //改变自己的样式
      $(event.target).removeClass('unselect')
      $(event.target).addClass('select')
      $(event.target).children("img").css("display","block")
      //$(event.target).append('<img style="width:24px;height:24px;" src="images/selected.png">')     
      //改变其他按钮，未选中->选中
      $(".choose").each(function(index){
        if($(this).children("img").length == 1){  //img displaynone,点击的是div,未选中->选中
          if(index != $('.choose').length - 1 ){
            $(this).removeClass('unselect')
            $(this).addClass('select')
            $(this).children("img").css("display","block")
          }        
        }
      });
    }
    else {     //点击的是img，选中->未选中
      //改变自己
      $(event.target).css("display","none")
      $(event.target).parent().removeClass('select')
      $(event.target).parent().addClass('unselect')
      //改变其他，选中->未选中
      $(".choose").each(function(index){
        if($(this).hasClass('select') == true){  //点击的是img,选中->未选中         
          $(this).children("img").css("display","none") 
          $(this).removeClass('select')
          $(this).addClass('unselect')      
        }
      });

    }
   
  },

  pay: function() {
    let arr = []
    $('.choose').each(function(){
      if($(this).hasClass("select") == true){
        let id = $(this).data('id');
        let idch = '#' + id ; 
        let amount = parseInt($(idch).text().substring(1,2)); 
        let elem = {
          id:id,
          amount:amount
        } 
        arr.push(elem)
      }
    });
    let url = `pay.html?tt=${JSON.stringify(arr)}`
    window.location.href=encodeURI(url);
  },

  jump: function() {
    window.location.href="index.html"; 
  }

};

$(function () {
  $(window).on('load',function () {
    App.init();
  });
});

